//
//  SXHBaseWebView.m
//  ZLZKBaseUtils
//
//  Created by sxh on 2020/12/9.
//

#import "SXHBaseWebView.h"
#import "BaseFunction.h"
#import "photos.h"
#import "speech.h"
#import "macro.h"
#import "SXHFileManager.h"
#import "NSObject+UIViewController.h"
#import "TipsHud.h"
#import "JSBUtil.h"

@implementation SXHBaseWebView

/// 初始化wkwebview
/// @param frame frame
/// @param configuration wkwebview配置项
- (instancetype)initWithFrame:(CGRect)frame
                configuration:(WKWebViewConfiguration *)configuration {
        
    [configuration setValue:@(YES) forKey:@"_allowUniversalAccessFromFileURLs"];
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSString *cookie = [NSString stringWithFormat:@"document.cookie=\'JSESSIONID=%@;path=/\'",sessionId];
    WKUserScript *script = [[WKUserScript alloc] initWithSource:cookie
                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                               forMainFrameOnly:NO];

    [configuration.userContentController addUserScript:script];
    
//    // 注入依赖库
//    NSData *moduleData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://unpkg.zhimg.com/s-bridge"]];
//    NSData *moduleData1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://unpkg.zhimg.com/vue@2.6.10/dist/vue.min.js"]];
//    NSString *moduleStr = [[NSString alloc] initWithData:moduleData encoding:NSUTF8StringEncoding];
//    NSString *moduleStr1 = [[NSString alloc] initWithData:moduleData1 encoding:NSUTF8StringEncoding];
//
//    NSString *module = [NSString stringWithFormat:@"%@%@", moduleStr, moduleStr1];
//    WKUserScript *moduleScript = [[WKUserScript alloc] initWithSource:module
//                                                  injectionTime:WKUserScriptInjectionTimeAtDocumentStart
//                                               forMainFrameOnly:NO];
//    [configuration.userContentController addUserScript:moduleScript];
    
    self = [super initWithFrame:frame configuration:configuration];
    
    if (self) {
        super.navigationDelegate = self;
        
        [self initView];
    }
    return self;
}

//初始化UI
- (void)initView {
    
    [self disableJavascriptDialogBlock:YES];

    // 监听JavaScript调用window.close
    [self setJavascriptCloseWindowListener:^{
        NSLog(@"触发了window.close");
    }];
    //禁止滑动
    [self.scrollView setBounces:NO];
    
    [self addAllJavaScriptObject];
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    
    //后续注入cookie
    NSString *sessionId = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    NSString *cookie = [NSString stringWithFormat:@"document.cookie=\'JSESSIONID=%@;path=/\'",sessionId];
    [webView evaluateJavaScript:cookie completionHandler:nil];
    
//    // 注入依赖库
//    NSData *moduleData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://unpkg.zhimg.com/s-bridge"]];
//    NSData *moduleData1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://unpkg.zhimg.com/vue@2.6.10/dist/vue.min.js"]];
//    NSString *moduleStr = [[NSString alloc] initWithData:moduleData encoding:NSUTF8StringEncoding];
//    NSString *moduleStr1 = [[NSString alloc] initWithData:moduleData1 encoding:NSUTF8StringEncoding];
//
//    NSString *module = [NSString stringWithFormat:@"%@%@", moduleStr, moduleStr1];
//
//    [webView evaluateJavaScript:module completionHandler:nil];
    
    if (self.sxhNavigationDelegate && [self.sxhNavigationDelegate respondsToSelector:@selector(webView:didStartProvisionalNavigation:)]) {
        [self.sxhNavigationDelegate webView:webView didStartProvisionalNavigation:navigation];
    }
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation {
    
    if (self.sxhNavigationDelegate && [self.sxhNavigationDelegate respondsToSelector:@selector(webView:didFinishNavigation:)]) {
        [self.sxhNavigationDelegate webView:webView didFinishNavigation:navigation];
    }
}

// 页面导航失败
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    if (self.sxhNavigationDelegate && [self.sxhNavigationDelegate respondsToSelector:@selector(webView:didFailNavigation:withError:)]) {
        [self.sxhNavigationDelegate webView:webView didFailNavigation:navigation withError:error];
    }
}

// 页面加载失败
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    
    if (self.sxhNavigationDelegate && [self.sxhNavigationDelegate respondsToSelector:@selector(webView:didFailProvisionalNavigation:withError:)]) {
        [self.sxhNavigationDelegate webView:webView didFailProvisionalNavigation:navigation withError:error];
    }
}

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler {
    
    if ([prompt containsString:@"accessNative"]) {
        
        NSDictionary *dic = [JSBUtil jsonStringToObject:defaultText];
        SXHBaseScriptMessage *message = [[SXHBaseScriptMessage alloc] initWithWebview:webView dict:dic completionHandler:completionHandler];
        
        if (self.delegate && [self.delegate respondsToSelector:@selector(webView:didReceiveScriptMessage:)]) {
            
            completionHandler([JSBUtil objToJsonString:@{@"code":@-1,@"data":@""}]);
            [self.delegate webView:self didReceiveScriptMessage:message];
        }else {
            
            completionHandler([JSBUtil objToJsonString:@{@"code": @"500", @"message": @"该方法未实现", @"data": @{}}]);
        }
    }else {
        
        [super webView:webView runJavaScriptTextInputPanelWithPrompt:prompt defaultText:defaultText initiatedByFrame:frame completionHandler:completionHandler];
    }
}

#pragma mark - event methods
//注入JavaScript对象
- (void)addAllJavaScriptObject {
    // 默认引入模块
    [self addJavascriptObject:[BaseFunction new] namespaces:@""];
    [self addJavascriptObject:[photos new] namespaces:@"b"];
    #if TARGET_IPHONE_SIMULATOR  //模拟器
    #elif TARGET_OS_IPHONE //真机
        [self addJavascriptObject:[speech new] namespaces:@"c"];
    #endif
}

- (void)loadingUrl:(NSString *)url {
    
    NSURL *fileUrl = [self urlWithAgreement:url];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:fileUrl];
    
    [self loadRequest:request];
}

//处理当前加载的url
- (NSURL *)urlWithAgreement:(NSString *)urlStr {
    //1.判断当前传入的url类型
    //2.文件类型处理沙盒目录
    //3.返回处理后的url
    if ([urlStr hasPrefix:@"http://"] || [urlStr hasPrefix:@"https://"]) {
        //http传输协议
        return [NSURL URLWithString:urlStr];
    }
    if ([urlStr hasPrefix:@"file:///"]) {
        //本地file协议
        NSString *urlString = [urlStr stringByReplacingOccurrencesOfString:@"file://" withString:@""];
        NSString *filePath = [urlString stringByDeletingLastPathComponent];
        
        NSString *hotVersion = kValueForKey(@"hotFixVersion") ? kValueForKey(@"hotFixVersion") : @"1";
        NSString *webVersion = [NSString stringWithFormat:@"%@.%@", AppVersion, hotVersion];
        //判断tmp下是否存在该目录 不存在则创建
        NSString *tmp = NSTemporaryDirectory();
        NSString *tmpWork = [NSString stringWithFormat:@"%@widget/", tmp];
        
        //目录不存在需要创建
        if (![[NSFileManager defaultManager] fileExistsAtPath:tmpWork]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:tmpWork
                                     withIntermediateDirectories:YES
                                                      attributes:nil
                                                           error:nil];
        }
        
        NSString *resultUrl = [NSString stringWithFormat:@"%@%@/", tmpWork, webVersion];
        //tmp目录下文件不存在则从工作目录拷贝一份
        if ([[NSFileManager defaultManager] fileExistsAtPath:resultUrl]) {
            
            // 若本地已存在文件 但是记录的版本号不一致 则清空重新拷贝
            if (![kValueForKey(@"fileWebVersion") isEqualToString:webVersion]) {
                
                [[NSFileManager defaultManager] removeItemAtPath:resultUrl error:nil];
                
                [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:resultUrl error:nil];
            }
        }else {
            
            [[NSFileManager defaultManager] copyItemAtPath:filePath toPath:resultUrl error:nil];
        }
    
        //避免特殊字符url转义 中文字符转义为空
        NSString *resultPath = [[@"file://" stringByAppendingString:resultUrl] stringByAppendingString:[urlStr lastPathComponent]];
        kSetValueForKey(webVersion, @"fileWebVersion");
        return [NSURL URLWithString:resultPath];
    }
    if ([urlStr containsString:@"://"]) {
        //其它的文件协议
        //切割出协议名和appid
        NSArray *agreements = [urlStr componentsSeparatedByString:@"://"];
        _agreement = agreements.firstObject;//协议名称
        NSMutableArray *appids = [agreements.lastObject componentsSeparatedByString:@"/"].mutableCopy;
        _appid = appids.firstObject;//appid
        //判断tmp下是否存在该目录 不存在则创建
        NSString *tmp = NSTemporaryDirectory();
        NSString *tmpWork = [NSString stringWithFormat:@"%@%@/%@/widget",tmp,_agreement,_appid];
        if (![[NSFileManager defaultManager] fileExistsAtPath:tmpWork]) {
            [[NSFileManager defaultManager] createDirectoryAtPath:tmpWork
                                     withIntermediateDirectories:YES
                                                      attributes:nil
                                                           error:nil];
        }
        //对index.html#/xxx?xxx特殊链接处理
        NSString *lastPath = agreements.lastObject;
        if ([lastPath containsString:@"#/"]) {
            
            NSMutableArray *lastPathArr = [lastPath componentsSeparatedByString:@"#/"].mutableCopy;
            lastPath = lastPathArr.firstObject;
        }
        //判断该文件协议在bundle中是否存在目录
        if ([[NSFileManager defaultManager] fileExistsAtPath:kBundleWidgets(_agreement, lastPath)] &&
            ![[NSFileManager defaultManager] fileExistsAtPath:kWidgetDirectory(_agreement, _appid)]) {
            //目录存在 在沙盒中创建对应目录并复制文件
            [[SXHFileManager sharedInstace] createWorkPath:_agreement withAppid:_appid];
            [[SXHFileManager sharedInstace] copyDirectoryToWorkPath:_agreement withAppid:_appid isForce:NO];
        }
        //删除第一个元素
        [appids removeObjectAtIndex:0];
        //appid工作目录+传入子目录或文件
//        NSString *resultUrl = [NSString stringWithFormat:@"%@/%@",kWidgetDirectory(_agreement, _appid),[appids componentsJoinedByString:@"/"]];
        NSString *resultUrl = [NSString stringWithFormat:@"%@/%@", tmpWork, [appids componentsJoinedByString:@"/"]];
        //tmp目录下文件不存在则从工作目录拷贝一份
        if (![[NSFileManager defaultManager] fileExistsAtPath:resultUrl]) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:tmpWork]) {
                
                [[NSFileManager defaultManager] removeItemAtPath:tmpWork error:nil];
            }
            [[NSFileManager defaultManager] copyItemAtPath:kWidgetDirectory(_agreement, _appid) toPath:tmpWork error:nil];
        }
        
        //获取当前本地web资源的版本号 若无则置初始值
        NSString *webVersionKey = [NSString stringWithFormat:@"%@+%@+%@", _agreement, _appid, AppVersion];
        if (!kValueForKey(webVersionKey)) {
            
            kSetValueForKey(@"1.0.0", webVersionKey);
        }
//        return [NSURL fileURLWithPath:resultUrl];
        //避免特殊字符url转义 中文字符转义为空
        NSString *resultPath = [@"file://" stringByAppendingString:resultUrl];
        return [NSURL URLWithString:resultPath];
        
    }
    return nil;
}

#pragma mark - getter && setter

- (void)setParams:(NSMutableDictionary *)params {
    _params = params;
}

@end
